//
//  M4Button.swift
//  M4
//
//  Created by YuChuang on 2024/8/6.
//

import Foundation
import UIKit


extension UIButton {
    
    class func initializeMethod() {
        let selector = #selector(UIButton.sendAction(_:to:for:))
        let newSelector = #selector(M4NewSendAction(_:to:for:))
        
        let method: Method = class_getInstanceMethod(UIButton.self, selector)!
        let newMethod: Method = class_getInstanceMethod(UIButton.self, newSelector)!
        
        if class_addMethod(UIButton.self, selector, method_getImplementation(newMethod), method_getTypeEncoding(newMethod)) {
            class_replaceMethod(UIButton.self, newSelector, method_getImplementation(method), method_getTypeEncoding(method))
        } else {
            method_exchangeImplementations(method, newMethod)
        }
    }
    
    
    @objc private func M4NewSendAction(_ action: Selector, to target: Any?, for event: UIEvent?) {
        if M4EventUnavailable == false {
            M4EventUnavailable = true
            M4NewSendAction(action, to: target, for: event)
            // 延时恢复
            DispatchQueue.main.asyncAfter(deadline: .now() + 0.5) {
                self.M4EventUnavailable = false
            }
        }
    }
    
    var M4EventUnavailable: Bool {
        get {
            if let unavailable = objc_getAssociatedObject(self, &M4AssociatedKeys.M4_EventUnavailable) as? Bool {
                return unavailable
            }
            return false
        }
        set {
            objc_setAssociatedObject(self, &M4AssociatedKeys.M4_EventUnavailable, newValue as Bool, .OBJC_ASSOCIATION_RETAIN_NONATOMIC)
        }
    }
    
    private struct M4AssociatedKeys {
        static var M4_EventUnavailable = "eventUnavailable"
    }
    
    
    func M4ButtonUnderline() {
        let text = self.titleLabel?.text ?? ""
        let fontSize = self.titleLabel?.font.pointSize ?? 10
        let attString = NSMutableAttributedString(string:text)
        let strRange = NSRange(location: 0, length: attString.length)
        let number = NSNumber(integerLiteral: NSUnderlineStyle.single.rawValue)
        let attrs = [NSAttributedString.Key.underlineStyle: number,
                     NSAttributedString.Key.foregroundColor: self.titleLabel?.textColor ?? .white,
                     NSAttributedString.Key.font: UIFont.systemFont(ofSize: fontSize)]
        attString.addAttributes(attrs, range: strRange)
        self.setAttributedTitle(attString, for: .normal)
    }
    
    
}
